package com.ruoyi.web.core.mybatis.driver;

import cn.hutool.core.util.StrUtil;
import com.ruoyi.web.core.mybatis.anno.SimpleIgnore;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.scripting.LanguageDriver;
import org.apache.ibatis.scripting.xmltags.XMLLanguageDriver;
import org.apache.ibatis.session.Configuration;

import java.util.Arrays;

public class SimpleUniqueDriver extends XMLLanguageDriver implements LanguageDriver {

    @Override
    public SqlSource createSqlSource(Configuration configuration, String script, Class<?> parameterType) {
        StringBuilder sql = new StringBuilder();
        String tableName = StrUtil.toUnderlineCase(parameterType.getSimpleName()).toLowerCase();
        sql.append("select * from ").append(tableName).append(" where 1=1 ");
        Arrays.stream(parameterType.getDeclaredFields())
                .filter(f -> !f.isAnnotationPresent(SimpleIgnore.class))
                .forEach(f -> {
                    String fn = f.getName();
                    sql.append("<if test=\"").append(fn).append(" != null\"> and ")
                            .append(StrUtil.toUnderlineCase(fn).toLowerCase()).append(" = #{").append(fn).append("}</if>");
                });
        sql.append(" limit 1 ");
        script = "<script>" + sql.toString() + "</script>";
        return super.createSqlSource(configuration, script, parameterType);
    }
}
